<template>
  <div class="createPost-container">
    <el-form
      ref="postFormNode"
      :model="postForm"
      :rules="rules"
      class="form-container"
    >
      <Sticky
        :z-index="10"
        :class-name="'sub-navbar ' + postForm.status"
      >
        <el-button
          v-loading="loading"
          style="margin-left: 10px"
          type="success"
          @click="submitForm"
        >
          提 交
        </el-button>
      </Sticky>

      <div class="createPost-main-container">
        <el-row>
          <Warning />

          <el-col :span="24">
            <el-form-item prop="titleContent">
            <MaterialInput
              :maxlength="100"
              :title="postForm.titleContent"
              @inputVal="inputVal"
              placeholder="方案名称"
            >
              
            </MaterialInput>
            </el-form-item>
            <div class="postInfo-container">
              <el-row>
                <el-col :span="8">
                  <el-form-item
                    label-width="60px"
                    label="编写人:"
                    class="postInfo-container-item"
                    prop="creatName" 
                  >
                    <el-input
                      v-model="postForm.creatName"
                      class="article-textarea"
                      autosize
                      placeholder="请输入编写人"
                    />
                  </el-form-item>
                </el-col>

                <el-col :span="10">
                  <el-form-item
                    label-width="120px"
                    label="编写时间:"
                    class="postInfo-container-item"
                     prop="creatTime" >
                    <el-date-picker
                      v-model="postForm.creatTime"
                      type="datetime"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>

        <el-form-item
          style="margin-bottom: 40px"
          label-width="70px"
          label="概要:"
           prop="abstractContent" 
        >
          <el-input
            v-model="postForm.abstractContent"
            :rows="1"
            type="textarea"
            class="article-textarea"
            autosize
            placeholder="请输入概要"
          />
          <!-- <span
            v-show="abstractContentLength"
            class="word-counter"
          >{{ abstractContentLength() }}</span> -->
        </el-form-item>
        
        
		<el-form-item label="参与人防工程："  prop="joinCompany" >
			<el-select placeholder="请选择" clearable class="w100" v-model="postForm.joinCompany">
				<el-option v-for="(item,index) in zhihuijigouArr" :key="index" :value="item.title"></el-option>
			</el-select>
		</el-form-item>
		
		<el-form-item label="参与专业队伍：" prop="joinGroup" >
			<el-select placeholder="请选择" clearable class="w100" v-model="postForm.joinGroup">
				<el-option v-for="(item,index) in zhuanyeduiwuArr" :key="index" :value="item.title"></el-option>
			</el-select>
		</el-form-item>
		
		<el-form-item label="所需战备物资："  prop="joinGoods" >
			<el-select placeholder="请选择" clearable class="w100" v-model="postForm.joinGoods">
				<el-option v-for="(item,index) in zhanbeiwuziArr" :key="index" :value="item.title"></el-option>
			</el-select>
		</el-form-item>
		
		
		<el-form-item label="关联经济目标：" prop="joinTarget" >
			<el-select placeholder="请选择" clearable class="w100" v-model="postForm.joinTarget">
				<el-option v-for="(item,index) in economicTargetsArr" :key="index" :value="item.title"></el-option>
				<!-- <el-option label="寿县市高速隧道" value="2"></el-option>
				<el-option label="寿县市自来水厂" value="3"></el-option> -->
			</el-select>
		</el-form-item>
		
        <el-form-item
          v-if="postForm.fullContent||isEdit==false"
          prop="fullContent"
          style="margin-bottom: 30px"
        >
        <!--
          <Tinymce
            ref="editor"
            :value="postForm.fullContent"
            :height="400"
          />
          -->
          <Editor :is-disable="false" v-model="postForm.fullContent" />
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script lang="ts">
import {
  reactive,
  toRefs,
  defineComponent,
  onDeactivated,
  onActivated,
  onBeforeMount,
  ref,
  unref,
  computed
} from 'vue'
import { isValidURL } from '/@/utils/validate'
import { getArticle, defaultArticleModel } from '/@/request/articles'
//import { getUsers } from '/@/api/user'
//import { TagView } from '@/store/modules/tagsview/state'
import MaterialInput from '/@/components/material-input/Index.vue'
import Sticky from '/@/components/sticky/Index.vue'
import Editor from '/@/components/editor/index.vue';
//import Tinymce from '/@/components/tinymce/Index.vue'
// import UploadImage from '@/components/UploadImage/index.vue'
import {
  CommentDropdown,
  PlatformDropdown,
  SourceUrlDropdown
} from './Dropdown'
import { ElMessage, ElForm } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import { useStore } from '/@/store'
import VoiceUnit from '/@/utils/shf/VoiceUnit'
import HttpReqApi from '/@/utils/shf/http/HttpReqApi'
//import { TagsActionTypes } from '@/store/modules/tagsview/action-types'

export default defineComponent({
  props: {
    isEdit: {
      type: Boolean,
      default: true
    }
  },
  components: {
    CommentDropdown,
    PlatformDropdown,
    SourceUrlDropdown,
    Sticky,
    MaterialInput,
    Editor
    //Tinymce,
    // UploadImage
  },

  setup(_, ctx) {
    console.log(ctx)
    const postFormNode = ref(ElForm)
    const validateRequire = (rule: any, value: string, callback: Function) => {
      if (value === '') {
         if(rule.field=="fullContent")
         {
           ElMessage.error({
            message: rule.field + ' is required',
            type: 'error'
          })
         }
        callback(new Error(rule.field + ' is required'))
      } else {
        callback()
      }
    }
    const validateSourceUrl = (rule: any, value: string, callback: any) => {
      if (value) {
        if (isValidURL(value)) {
          callback()
        } else {
          ElMessage.error({
            message: 'Invalid URL',
            type: 'error'
          })
          callback(new Error('Invalid URL'))
        }
      } else {
        callback()
      }
    }
    const store = useStore()

    const route = useRoute()
    const dataMap = reactive({
      zhihuijigouArr:[],
      zhuanyeduiwuArr:[],
      zhanbeiwuziArr:[],
      economicTargetsArr:[],
      articleId:-1,
      router: useRouter(),
      route: route,
      postForm: {
        joinCompany:"无",
        joinGroup:"无",
        joinGoods:"无",
        joinTarget:"无",
        creatName:"",
        titleContent:"",
        abstractContent:"",
        fullContent:"",
        creatTime:""
      },
      loading: false,
      userListOptions: [],
      value: '',
      rules: {
        joinCompany:[{ validator: validateRequire }],
        joinGroup:[{ validator: validateRequire }],
        joinGoods:[{ validator: validateRequire }],
        joinTarget:[{ validator: validateRequire }],
        creatName:[{ validator: validateRequire }],
        titleContent:[{ validator: validateRequire }],
        abstractContent:[{ validator: validateRequire }],
        fullContent:[{ validator: validateRequire }],
        creatTime:[{ validator: validateRequire }]
      },

      tinymceActive: true,
      abstractContentLength() {
        return this.postForm.abstractContent.length
      },
      lang() {
        return store.state.app.language
      },
      formDropdown: (val: any) => {
        dataMap.postForm.platforms = val
      },
      inputUrl: (val: any) => {
        dataMap.postForm.sourceURL = val
      }
      // set and get is useful when the data
      // returned by the backend api is different from the frontend
      // e.g.: backend return => "2013-06-25 06:59:25"
      //       frontend need timestamp => 1372114765000
    })

    const timestamp = computed(() => {
      return +new Date(dataMap.postForm.timestamp)
    })

    const setPageTitle = (title: string) => {
      document.title = `${title} - ${dataMap.postForm.id}`
    }
    
    const fetchData = async(id: any) => {
      try {
       let data:any = await  HttpReqApi.getHelpschemeOne({id});
       if(data)
       {
        dataMap.postForm = {...data,fullContent:data.joinContent};
       }       
        // const data = await getArticle({ id })
        // if (data) {
        //   console.log(data.data)

        //   dataMap.postForm = data.data
        //   dataMap.postForm.author = data.data.author
        // }

        // console.log(dataMap.postForm, 'authorauthorauthorauthorauthor')
        // dataMap.value = String(data?.data.timestamp)

        // // Just for test
        // dataMap.postForm.title += `   Article Id:${dataMap.postForm.id}`
        // dataMap.postForm.abstractContent += `   Article Id:${dataMap.postForm.id}`
        // const title = dataMap.lang() === 'zh' ? '编辑文章' : 'Edit Article'
        // // Set tagsview title
        // // Set page title
        // setPageTitle(title)
      } catch (err) {
        // console.error(err)
      }
    }

    const submitForm = () => {
      const form = unref(postFormNode)
      form.validate(async (valid: any) => {
        if (valid) {
          // console.log("fullContent = ",dataMap.postForm.fullContent);
          // console.log({...dataMap.postForm});
          
         dataMap.loading = true;
         setTimeout(() => {
            dataMap.loading = false
          }, 0.5 * 1000)

         if(_.isEdit)
         {
            await HttpReqApi.updateHelpscheme({...dataMap.postForm,joinContent:dataMap.postForm.fullContent,id:dataMap.articleId});
            ElMessage.success({
              message: '修改成功',
              type: 'success',
              duration: 2000
            });
            dataMap.router.back();
            return;
         }
         await HttpReqApi.addHelpscheme({...dataMap.postForm,joinContent:dataMap.postForm.fullContent});
          ElMessage.success({
            message: '提交成功',
            type: 'success',
            duration: 2000
          })
          dataMap.router.back();
          // dataMap.postForm.status = 'published'
          // // Just to simulate the time of the request
          
        } else {
          console.error('Submit Error!')
          return false
        }
      })
    }

    const draftForm = () => {
      if (
        dataMap.postForm.fullContent.length === 0 ||
        dataMap.postForm.title.length === 0
      ) {
        ElMessage.warning({
          message: 'Title and detail content are required',
          type: 'warning'
        })
        return
      }
      ElMessage.success({
        message: 'The draft saved successfully',
        type: 'success',
        showClose: true,
        duration: 1000
      })
      dataMap.postForm.status = 'draft'
    }
    
    const inputVal = (val: any) => {
      dataMap.postForm.titleContent = val
    }

    onDeactivated(() => {
      dataMap.tinymceActive = false
    })
    onActivated(() => {
      dataMap.tinymceActive = true
    })
    onBeforeMount(async() => {
      let list1:any = await HttpReqApi.getEconomicTargets();
      let list2:any = await HttpReqApi.getZhanbeiwuzi();
      let list3:any = await HttpReqApi.getZhuanyeduiwu();
      let list4:any = await HttpReqApi.getZhihuijigou();

      dataMap.economicTargetsArr = list1;
      dataMap.zhanbeiwuziArr = list2;
      dataMap.zhuanyeduiwuArr = list3;
      dataMap.zhihuijigouArr = list4;

      if (_.isEdit) {
        const id:any = dataMap.route.query && dataMap.route.query.id
        fetchData(id)
        console.log("isEdit id = ",id);
        dataMap.articleId = id;
      }

      // Why need to make a copy of this.$route here?
      // Because if you enter this page and quickly switch tag, may be in the execution of this.setTagsViewTitle function, this.$route is no longer pointing to the current page
      // https://github.com/PanJiaChen/vue-element-admin/issues/1221
      // tempTagView = Object.assign({}, dataMap.route)
    })

    return {
      ...toRefs(dataMap),
      validateRequire,
      validateSourceUrl,
      fetchData,
      submitForm,
      setPageTitle,
      draftForm,
      postFormNode,
      timestamp,
      inputVal
    }
  }
})
</script>

<style lang="scss">
.article-textarea {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
</style>

<style lang="scss" scoped>
@mixin clearfix {
    &::after {
        content: "";
        clear: both;
        display: table;
    }
}

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      margin-top: 50px;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}
</style>
